<?php
/**
 * 鉴权中间件
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);

namespace app\admin\middleware;

use Webman\MiddlewareInterface;
use app\admin\model\AdminUser;
use Webman\Http\Response;
use Webman\Http\Request;

class AdminAuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $url = $request->request_url;

        $url_lower    = strtolower($url);
        $except_lower = array_map('strtolower', array_merge(ADMIN_LOGIN_EXCEPT, ADMIN_AUTH_EXCEPT));
        $need_check   = !in_array($url_lower, $except_lower, false);

        // 需要验证登录
        if ($need_check) {
            // 没有用户信息
            if(!isset($request->user) ){
                $redirect  = $url . '';
                $login_url = '/admin/auth/login?redirect=' . $redirect;

                return $request->method() === 'GET' ? redirect($login_url) : admin_error('获取登录用户信息失败', $login_url);
            }

            // 验证权限
            if($request->user->id !== 1 && !$this->checkPermission($request->user, $url)) {
                return $request->method() === 'GET' ? redirect('/admin/error/err403') : admin_error('无权限');
            }

            // 如果是提前验证权限
            if ($request->input('check_auth')) {
                return admin_success('验证权限成功', [], URL_CURRENT);
            }
        }

        return $handler($request);
    }

    /**
     * 权限检查
     * @param AdminUser $user
     * @param string $url
     * @return bool
     */
    public function checkPermission(AdminUser $user, string $url): bool
    {
        $url    = strtolower($url);
        $except = array_map('strtolower', ADMIN_AUTH_EXCEPT);
        return in_array($url, $except, true) || in_array($url, array_map('strtolower', $user->auth_url), true);
    }
}
